/*
 * By Luocheng Tang
 */
package com.lvmama.vst.batis.dsobject;

import java.lang.reflect.Method;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataSourceUtil {
	public static final String DRUID_DATA_SOURCE = "com.alibaba.druid.pool.DruidDataSource";
	public static final String TOMCAT_DATA_SOURCE = "org.apache.tomcat.jdbc.pool.DataSource";
	
	private static Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);

	
	@SuppressWarnings("unchecked")
	public static Class<? extends DataSource> classInClasspath(String classname) {
		try {
			return (Class<? extends DataSource>)Class.forName(classname);
		} catch (ClassNotFoundException e) {
		}
		return null;
	}

	public static DataSource objToDataSource(Class<? extends DataSource> targetClass, DsObject dsObject) throws Exception {

		Object objTarget = targetClass.newInstance();
		Map<String, Object> map = dsObject.getConfigedFields();

		for (String setName : map.keySet()) {
			try {
				Object value = map.get(setName);
				String typeStr = value.getClass().getSimpleName();
				String getName = "g" + setName.substring(1);
				if ("Boolean".equalsIgnoreCase(typeStr)) {
					getName = "is" + setName.substring(3);
				}
				Class<?> returnType2 = targetClass.getMethod(getName).getReturnType();
				Method m2 = targetClass.getMethod(setName, returnType2);
				m2.invoke(objTarget, new Object[] { map.get(setName) });

			} catch (Exception ex) {
			}
		}
		DataSource ds = (DataSource) objTarget;
		logger.info(ds.toString());
		return ds;
	}
}
